//-----------------------------------------------------------------------
//  This file is part of the Microsoft Robotics Studio Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  $File: visionprocessing.cs $ $Revision: 1 $
//-----------------------------------------------------------------------

using System.IO;
using Microsoft.Robotics.PhysicalModel;
using System;
using System.Drawing;

namespace ProMRDS.SimpleSoccerPlayer
{

    public class ImageSegment
    {
        public float Saturation;
        public float SaturationEpsilon;
        public float Hue;
        public float HueEpsilon;
        public float Area;
        public float X;
        public int XMin;
        public int XMax;
        public int XSpan;
    }

    public static class ImageProcessing
    {
        /// <summary>
        /// Find objects in the image, using the segment definitions provided
        /// </summary>
        public static void ProcessFrameHandler(
            float width,
            float height,
            ImageSegment [] segments,
            byte[] rgbValues)
        {
            // initialize the results
            foreach (ImageSegment segment in segments)
            {
                segment.Area = segment.X = 0;
                segment.XMax = 0;
                segment.XMin = (int)(width + 1);
            }

            // scan the image
            int offset = 0;

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int r, g, b;

                    b = rgbValues[offset++];
                    g = rgbValues[offset++];
                    r = rgbValues[offset++];

                    Color color = Color.FromArgb(r, g, b);

                    float hue = color.GetHue();
                    float saturation = color.GetSaturation();

                    foreach (ImageSegment segment in segments)
                    {
                        if ((Math.Abs(hue - segment.Hue) < segment.HueEpsilon) &&
                            (Math.Abs(saturation - segment.Saturation) < segment.SaturationEpsilon))
                        {
                            segment.Area++;
                            segment.X += x;
                            segment.XMax = Math.Max(segment.XMax, x);
                            segment.XMin = Math.Min(segment.XMin, x);
                        }
                    }
                }
            }

            foreach (ImageSegment segment in segments)
            {
                if (segment.Area > 0)
                {
                    segment.X = segment.X / segment.Area;
                    segment.XSpan = segment.XMax - segment.XMin;
                }
            }
        }
    }
}